package com.shenyuan.module_basekt.api.fastjson

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.parser.Feature
import okhttp3.ResponseBody
import okio.Okio
import retrofit2.Converter
import java.lang.reflect.Type

/**
 * @author ch
 * @date 2022/7/15-14:28
 * desc
 */
class FastJsonResponseBodyConverter<T>(val type: Type) : Converter<ResponseBody, T> {

    override fun convert(value: ResponseBody): T? {
        val buffer = Okio.buffer(value.source())
        val jsonString = buffer.readUtf8()

        try {
            val obj = JSON.parseObject(jsonString)
            val code = obj.getString("code")
            val msg = obj.getString("msg")
            if ("1" == code) {
                val data = obj.get("data")
                if ("String" == type.javaClass.simpleName) {
                    return msg as T
                }
                if (data is String) {
                    return data as T
                }
                return JSON.parseObject(obj.getString("data"), type, Feature.SupportNonPublicField)
            } else {
                throw RuntimeException(msg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            throw e
        } finally {
            value.close()
            buffer.close()
        }
    }
}